package com.huatai.user.dubbo;

import cn.hutool.extra.pinyin.PinyinUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huatai.common.util.BeanUtil;
import com.huatai.user.dto.WeChatPeopleDto;
import com.huatai.user.entity.Department;
import com.huatai.user.entity.User;
import com.huatai.user.entity.UserRole;
import com.huatai.user.mapper.UserMapper;
import com.huatai.user.service.DepartmentService;
import com.huatai.user.service.UserRoleService;
import com.huatai.user.service.UserService;
import com.huatai.user.vo.UserVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.*;

import static com.huatai.user.constant.UserConstant.PMP_ID;

/**
 * @program: ht-system
 * @description: 用户暴露dubbo接口
 * @author: songxiude
 * @create: 2023-02-06 14:02
 **/
@DubboService
public class UserDubboApiServiceImpl implements UserDubboApi{
	@Autowired
	private UserService userService;
	@Autowired
	private PasswordEncoder passwordEncoder;
	@Value("${ht.user.dfpassword}")
	private String dfpassword;
	@Autowired
	private UserRoleService userRoleService;
	@Autowired
	private DepartmentService departmentService;

	private final int insertBatch = 40;
	@Autowired
	private UserMapper userMapper;

	@Override
	public UserVo findUserInfo(String username) {
		User user = userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getAccount, username));
		return BeanUtil.copy(user,UserVo.class);
	}

	@Override
	public UserVo findUserInfoByRealName(String username) {
		User user = userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getRealName, username));
		return BeanUtil.copy(user,UserVo.class);
	}

	@Override
	public List<User> saveUserByWeChatUserBpmn(Long updateUserId,Set<WeChatPeopleDto> userSet, Map<String, Long> roleIdMap) {
		LambdaQueryWrapper<User> userWrapper =  Wrappers.lambdaQuery();
		userWrapper.eq(User::getIsDeleted,0)
			.eq(User::getStatus,0);
		List<User> allUsers = userService.list(userWrapper);
		Set<WeChatPeopleDto> removeList = new HashSet<>(userSet.size());
		//剔除已有用户不进行新增
		for (User user : allUsers) {
			for (WeChatPeopleDto weChatPeopleDto : userSet) {
				if (weChatPeopleDto.getUserid().equals(user.getAccount())) {
					removeList.add(weChatPeopleDto);
				}else if (weChatPeopleDto.getName().equals(user.getRealName())){
					removeList.add(weChatPeopleDto);
				}
			}
		}
		userSet.removeAll(removeList);
		List<User> newUser = new ArrayList<>();
		List<User> resultUser = new ArrayList<>();
		//添加新增用户集合
		for (WeChatPeopleDto weChatPeopleDto : userSet) {
			User user = new User();
			String name = PinyinUtil.getPinyin(weChatPeopleDto.getName()).replaceAll(" ", "");
			user.setAccount(name);
			user.setRealName(weChatPeopleDto.getName());
			user.setUpdateUserid(updateUserId);
			user.setCreateUserid(updateUserId);
			user.setStatus(0);
			user.setIsDeleted(0);
			user.setId(IdWorker.getId());
			weChatPeopleDto.setId(user.getId());
			//创建用户时给默认密码
			user.setPassword(passwordEncoder.encode(dfpassword));
			newUser.add(user);
			resultUser.add(user);
			if (newUser.size()>=insertBatch){
				userService.saveBatch(newUser);
				newUser.clear();
			}
		}
		userService.saveBatch(newUser);
		//为新增用户绑定默认的事项管理中心角色
		List<UserRole> newUserRoleList = new ArrayList<>();
		for (WeChatPeopleDto weChatPeopleDto : userSet) {
			String position = weChatPeopleDto.getPosition();
			List<Long> roleIds = new ArrayList<>();
			Long tjjs = roleIdMap.get("tjjs");
			Long ptjs = roleIdMap.get("ptjs");
			if (position.contains("总经理") || position.contains("主任") || position.contains("总工程师") || position.contains("主管")) {
				roleIds.add(tjjs);
				roleIds.add(ptjs);
			}else {
				roleIds.add(ptjs);
			}
			roleIds.forEach(aLong -> {
				UserRole userRole = new UserRole();
				userRole.setUserId(weChatPeopleDto.getId());
				userRole.setRoleId(aLong);
				newUserRoleList.add(userRole);
			});
		}
		userRoleService.saveBatch(newUserRoleList);
		return resultUser;
	}

	@Override
	public User saveOrUpdate(User user) {

		return null;
	}

	@Override
	public List<User> getList() {
		List<User> list = userService.list();
		return list;
	}

	@Override
	public Department getDepart(Long deptId) {
		Department department = departmentService.getById(deptId);
		return department;
	}
	/**
	 * 查询部门用户id
	 * @param deptId
	 * @return
	 */
	@Override
	public List<User> getDepartUser(Long deptId) {
		return userService.list(Wrappers.<User>lambdaQuery().eq(User::getDeptId,deptId));
	}

	@Override
	public List<JSONObject> getDepartList() {
		return departmentService.getDepartList();
	}

	@Override
	public User getUser(Long creator) {
		return userService.getById(creator);
	}


	/**
	 * 获取用户角色是否有所有查看数据
	 * @param userId
	 * @return
	 */
	@Override
	public boolean getRoleByUserId(Long userId) {

		return userMapper.getRoleByUserId(userId, PMP_ID);
	}

}
